package com.health.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.health.AddCustomerActivity;
import com.health.MainActivity_Menu_Tj;
import com.health.NovaApplication;
import com.health.R;
import com.health.adapter.DoctorAdapter;
import com.health.adapter.XZ_CZHospitalAdapter;
import com.health.db.FDbManager;
import com.health.model.DZJMJKKSQCodeImageBean;
import com.health.model.DZJMJKKXQcodeBean;
import com.health.model.DZJMJKKXcrzBean;
import com.health.model.PeopleType;
import com.health.activity.qyinfo.QYInfo;
import com.health.activity.settings.SystemSettingJMDZDAActivity;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.BD_DD_INFO;
import com.health.tablebean.BD_ORGANIZE_EMPLOYEE;
import com.health.tablebean.BD_ORGANIZE_INSTITUTION;
import com.health.tablebean.HD_PERSONAL_JKTZ;
import com.health.tablebean.JTYSCustomerDoctorCont;
import com.health.tablebean.JTYS_BASEINFO;
import com.health.tools.GlobalConts;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.IDCardVerifyTool;
import com.health.tools.SPUtil;
import com.health.view.spinner.NiceSpinner;
import com.health.viewscontrols.CaptureActivity;
import com.health.webservices.JmdzjkkWebService;
import com.health.webservices.WebServiceConts;
import com.health.webservices.dzjmjkkxml.DzjmjkkDataTool;
import com.health.widget.CommomDialog;
import com.health.widget.EditTextWithDate;
import com.litesuits.http.data.Json;
import com.nova.view.NovaTextDialog;
import com.zkteco.id300.IDCardReader;
import com.zkteco.id300.meta.IDCardInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.novabluetooth.services.ktxyj.Constants.AREA_CODE;

/**
 * 新建档案（弹框）
 *
 * @author nova
 */
public class Main_tj_loginFragment2 extends NovaFragment implements OnClickListener, AdapterView.OnItemSelectedListener {
    private boolean scanSuccess = false;
    private static final String TAG = "Main_tj_loginFragment";
    private static final String ISTAG = "1";
    private NiceSpinner minzuSpinner;
    private Button btn_read_idcard;//读卡
    private Button btn_finish_add;
    private Button btn_close;
    private EditText idNoEt;
    private EditText nameEt;
    private EditTextWithDate birthdayEt;
    private EditText addressEt;
    private RadioGroup sexRadio;
    protected String sex;
    private RadioButton mailRadio;
    private RadioButton famailRadio;
    private ARCHIVE_BASEINFO userInfo = new ARCHIVE_BASEINFO();
    private View baseView;
    FDbManager fDbManager = NovaApplication.fdbmanger;
    private boolean flag_fromIdCard = false;
    public static int CAMERA_REQUEST_CODE = 1;
    private int age;

    private EditText exam_phone;

    private LinearLayout linear_sfycf;
    private CheckBox check_isycf;
    private ImageView iv_photo;
    private ImageView iv_smjmdzjkk;
    private ProgressDialog mProgressDialog;

    IDCardReader idCardReader = null;
    boolean mbStop = true;
//    private WorkThread workThread = null;
    BluetoothAdapter mBluetoothAdapter;// ble
    BluetoothManager mBluetoothManager;

    /**
     * 顶部信息相关
     **/
    private List<BD_ORGANIZE_INSTITUTION> listCS_Hospital = new ArrayList<BD_ORGANIZE_INSTITUTION>();// 城市医院
    // ------------机构及人员-----------------
    /**
     * 4乡镇医院
     */
    private Spinner sp01;
    private List<BD_ORGANIZE_INSTITUTION> lstData01 = new ArrayList<BD_ORGANIZE_INSTITUTION>();
    private String code01 = "";
    private String name01 = "";

    /**
     * 5村庄医院
     */
    private Spinner sp02;
    private List<BD_ORGANIZE_INSTITUTION> lstData02 = new ArrayList<BD_ORGANIZE_INSTITUTION>();
    private String code02 = "";
    private String name02 = "";

    /**
     * 机构编号
     */
    private EditText edJgId;
    private String str_QuId = "";// 行政区id

    /**
     * 医生、村庄医院 、建档人
     */
    private Spinner spDoc;
    private List<BD_ORGANIZE_EMPLOYEE> listDoc = new ArrayList<BD_ORGANIZE_EMPLOYEE>();
    private String docName = "";
    private String docId = "";
    private String docPassward = "";
    private String docUsername = "";
    private String docIDCard = "";

    /**
     * 医生id
     */
    private EditText edDocId;
    /**
     * 医生名称
     */
    private TextView tvDocName;
    // -------------机构及人员--------------

    @Override
    public View findViews(LayoutInflater inflater) {
        // userInfo = NovaApplication.userInfo;
        baseView = inflater.inflate(R.layout.mainactivity_login_tj, null);
//        }

        initBlooth();
        findViews(baseView);
        Log.e("123456789",
                "NovaApplication.getStr_dzjmjkk_url()" + NovaApplication.getStr_dzjmjkk_url() + "\n"
                        + "NovaApplication.isBoolean_dzjmjkk()" + NovaApplication.isBoolean_dzjmjkk() + "12"
                        + SPUtil.getstr_jdrIdcard(getActivity()));

        setData();
        return baseView;
    }

    //connect和disconnect都是hide方法，普通应用只能通过反射机制来调用该方法
    private void connect() {
        try {
            if (idCardReader != null) {
                idCardReader.closeDevice();
            } else {
                idCardReader = new IDCardReader();
                if (mBluetoothAdapter != null) {
                    Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
                    for (BluetoothDevice device : devices) {
                        if (device.getName().contains("ID300")) {
                            idCardReader.setDevice(device.getAddress());
                        }
                    }
                }

            }
        } catch (Exception e) {
            showTextDialog("请检查设备是否运行正常");
            idCardReader = null;
            return;
        }

        int i = idCardReader.openDevice();
        Log.e("555555555", i + "");
        if (i == 0) {
            showTextDialog("读卡器连接成功");
            mbStop = false;
            while (!mbStop) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //新建一个Message对象，存储需要发送的消息
                        Message message = new Message();
                        message.what = 1;
                        //然后将消息发送出去
                        handler.sendMessage(message);
                    }
                }).start();
            }
//            workThread = new WorkThread();
//            workThread.start();// 线程启动
        }

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (!ReadCardInfo()) {
                        Log.e("**********", "请放卡...");
                    } else {
                        Log.e("**********", "读卡成功，请放入下一张卡");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void setupView(View view) {

    }

    @Override
    public void addListener() {
        iv_smjmdzjkk.setOnClickListener(this);
        btn_read_idcard.setOnClickListener(this);
        btn_finish_add.setOnClickListener(this);
        btn_close.setOnClickListener(this);
        birthdayEt.setOnClickListener(this);

        sp02.setOnItemSelectedListener(this);
        sp01.setOnItemSelectedListener(this);

        sexRadio.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (mailRadio.getId() == checkedId || famailRadio.getId() == checkedId) {
                    int radioButtonId = group.getCheckedRadioButtonId();
                    // 根据ID获取RadioButton的实例
                    RadioButton rb = (RadioButton) getActivity().findViewById(radioButtonId);
                    // sex = rb.getText().toString();
                    if (checkedId == R.id.exam_mail) {
                        sex = "男";
                    } else if (checkedId == R.id.exam_famail) {
                        sex = "女";
                    }
                    if ("女".equals(sex)) {
                        iv_photo.setImageResource(R.drawable.head_youth_y);
                    } else {
                        iv_photo.setImageResource(R.drawable.head_youth_x);
                    }
                    Log.e("tag", sex + "");
                    setISycfVisible(sex);
                }
            }
        });

        idNoEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String idNo = idNoEt.getText().toString();
                String idCard18 = null;
                if (idNo.length() == 15) {
                    if (IDCardVerifyTool.Validate(idNo).equals("")) {
                        idCard18 = IDCardVerifyTool.from15to18(19, idNo);
                    }
                } else if (idNo.length() == 18) {
                    idCard18 = idNo;
                }
                if (idCard18 != null && idCard18.length() == 18) {
                    String info = IDCardVerifyTool.Validate(idNo);
                    if (info.equals("")) {
                        // 正确的身份证号
                        Log.w("ddddd", "eeeeeeeee" + idCard18);
                        List<ARCHIVE_BASEINFO> idCardList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                                "IDCARD = '" + idCard18 + "'");
                        String year = idCard18.substring(6, 10);
                        String mouth = idCard18.substring(10, 12);
                        String day = idCard18.substring(12, 14);
                        String birthdayStr = year + "-" + mouth + "" + "-" + day;
                        birthdayEt.setText(birthdayStr);

                        Calendar c = Calendar.getInstance();
                        age = c.get(Calendar.YEAR) - Integer.parseInt(year);

                        String sexStr = idCard18.substring(16, 17);
                        if (Integer.parseInt(sexStr) % 2 == 0) {
                            famailRadio.setChecked(true);
                        } else {
                            mailRadio.setChecked(true);
                        }

                        if (idCardList.size() > 0) {
                            // 身份证号已存在
                            Log.w("ddddd", "eeeeeeeee");
                            ((AddCustomerActivity) getActivity()).showTextDialog("数据已存在，不需要建档");
                            String strWhere = "IDCARD LIKE '" + idCard18 + "'";
                            List<ARCHIVE_BASEINFO> infos = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class, strWhere);
                            if (infos.size() > 0) {
                                NovaApplication.setUserInfo(infos.get(0));
                                Intent intent = new Intent(getActivity(), MainActivity_Menu_Tj.class);
                                getActivity().startActivity(intent);
                                cleanData();
                            }

                            return;
                        } else {
                            if (!flag_fromIdCard) {
                                // 如果不是从身份证读卡器读取
                                addressEt.setText("");
                                nameEt.setText("");
                                userInfo = new ARCHIVE_BASEINFO();
                            }
                        }

                    } else {
                        new AlertDialog.Builder(getActivity()).setTitle("温馨提示").setMessage(info + "请重新输入！")
                                .setPositiveButton("确定", null).show();
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        exam_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String mobile = exam_phone.getText().toString();
                if (mobile.length() == 11) {
                    if (!GlobalConts.isPhoneNumberValid(mobile)) {
                        ((AddCustomerActivity) getActivity()).showTextDialog("请输入正确的手机号码");
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    public void setData() {
        List<BD_DD_INFO> minzuList = fDbManager.findAllByWhereInInfoDB(BD_DD_INFO.class, "PARENTID = 'DM01-01'");
        List<String> minzu = new ArrayList<String>();
        if (minzuList != null) {
            for (BD_DD_INFO info : minzuList) {
                minzu.add(info.getDATAINFO());

            }
        }
        minzuSpinner.attachDataSource(minzu);
        minzuSpinner.setText("汉族");

        NovaApplication.setXzqhNo(AREA_CODE);
        getCS_XZ_Hospital(0, NovaApplication.getXzqhNo().substring(0, 4));
    }

    public void findViews(View view) {
        idNoEt = (EditText) baseView.findViewById(R.id.exam_login_idcard_et);
        nameEt = (EditText) baseView.findViewById(R.id.exam_name_et);
        sexRadio = (RadioGroup) baseView.findViewById(R.id.exam_sex);
        mailRadio = (RadioButton) baseView.findViewById(R.id.exam_mail);
        famailRadio = (RadioButton) baseView.findViewById(R.id.exam_famail);
        birthdayEt = (EditTextWithDate) baseView.findViewById(R.id.exam_birthday);
        birthdayEt.setDatePickerEnabled(false);
        birthdayEt.setClickable(false);
        addressEt = (EditText) baseView.findViewById(R.id.exam_address);
        minzuSpinner = (NiceSpinner) baseView.findViewById(R.id.exam_minzu_spinner);
        btn_read_idcard = (Button) baseView.findViewById(R.id.btn_read_idcard);
        btn_close = (Button) baseView.findViewById(R.id.btn_close);
        btn_finish_add = (Button) baseView.findViewById(R.id.btn_finish_add);
        birthdayEt.setBefore(new Date());

        exam_phone = (EditText) view.findViewById(R.id.exam_phone);
        linear_sfycf = (LinearLayout) view.findViewById(R.id.linear_sfycf);
        check_isycf = (CheckBox) view.findViewById(R.id.check_isycf);
        iv_photo = (ImageView) view.findViewById(R.id.iv_photo);
        iv_smjmdzjkk = (ImageView) view.findViewById(R.id.iv_smjmdzjkk);

        //顶部选择

        sp01 = (Spinner) view.findViewById(R.id.spinner_xz);
        sp02 = (Spinner) view.findViewById(R.id.spinner_cz);
        edJgId = (EditText) view.findViewById(R.id.ed_hospitalname);
        spDoc = (Spinner) view.findViewById(R.id.spinner_employee);
        edDocId = (EditText) view.findViewById(R.id.ed_userid);
        tvDocName = (TextView) view.findViewById(R.id.tv_username);
        if (NovaApplication.isBoolean_dzjmjkk()) {
            // 设置可见
            iv_smjmdzjkk.setOnClickListener(this);
            iv_smjmdzjkk.setVisibility(View.VISIBLE);
        } else {
            iv_smjmdzjkk.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_smjmdzjkk:
                getQuanXian();
                break;
            case R.id.btn_close://关闭
                getActivity().finish();
                break;
            case R.id.btn_finish_add://完成
                loginData();
                break;
            case R.id.btn_read_idcard://读卡器
                connect();
                break;
            default:
                break;
        }

    }

    public void setIdInfo(String data) {
        flag_fromIdCard = true;
        String[] infos = data.split(",");
        System.out.println();
        nameEt.setText(infos[0]);
        minzuSpinner.setText(infos[2]);
        addressEt.setText(infos[4]);
        idNoEt.setText(infos[5]);
    }

    /**
     * 清空数据
     *
     * @author 王婷婷
     * @date 2017年6月5日 下午2:55:03
     */
    private void cleanData() {
        nameEt.setText("");
        minzuSpinner.setText("汉族");
        addressEt.setText("");
        idNoEt.setText("");
        birthdayEt.setText("");
        sexRadio.clearCheck();
        exam_phone.setText("");
        check_isycf.setChecked(false);

        age = -1;
        sex = "";
    }

    /**
     * 新建提交
     *
     * @author 王婷婷
     * @date 2017年6月5日 下午2:56:59 民族
     */
    private void loginData() {
        String idNo = idNoEt.getText().toString().trim();
        String name = nameEt.getText().toString().trim();
        String birthday = birthdayEt.getText().toString().trim();
        String addr = addressEt.getText().toString().trim();
        String minzu = minzuSpinner.getText().toString().trim();
        String phone = exam_phone.getText().toString().trim();

        if (TextUtils.isEmpty(idNo) || TextUtils.isEmpty(name) || TextUtils.isEmpty(birthday) || TextUtils.isEmpty(addr)
                || TextUtils.isEmpty(minzu) || TextUtils.isEmpty(phone)) {
            ((AddCustomerActivity) getActivity()).showTextDialog("请将信息填写完整");
            return;
        }
        if (idNo.length() != 10) {
            if (!TextUtils.isEmpty(IDCardVerifyTool.Validate(idNo))) {
                ((AddCustomerActivity) getActivity()).showTextDialog("身份证号码错误，请修改再试");

                return;
            }
        }

        if (!GlobalConts.isPhoneNumberValid(phone)) {
            ((AddCustomerActivity) getActivity()).showTextDialog("请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(docName) || TextUtils.isEmpty(docId)) {
            showTextDialog("请选择机构及人员");
            return;
        }
        List<ARCHIVE_BASEINFO> idCardList = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class,
                "IDCARD = '" + idNo + "'");
        if (idCardList.size() == 0) {

            userInfo = new ARCHIVE_BASEINFO();
            userInfo.setPHONE(phone);
            userInfo.setADDR(addr);
            saveUserInfo(idNo, name, birthday, addr, minzu);
            try {
                userInfo.setCREATED_DATE(
                        GlobalConts.datetimeFormat.parse(GlobalConts.datetimeFormat.format(new Date())));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //保存所在村的单位信息
//            saveDanweiInfo();
            saveUserOrg();
            saveJBLX();
            showTextDialog("注册完成");
            String strWhere = "IDCARD LIKE '" + userInfo.getIDCARD() + "'";
            Log.e("身份证", userInfo.getIDCARD());
            List<ARCHIVE_BASEINFO> infos = fDbManager.findAllByWhere(ARCHIVE_BASEINFO.class, strWhere);
            if (infos.size() > 0) {
                fDbManager.delete(infos.get(0));
            }
            NovaApplication.setUserInfo(userInfo);
            fDbManager.save(userInfo);
//            getCJDAData(minzu);// 进行数据创建

            // 创建电子虚拟卡
            if (NovaApplication.isBoolean_dzjmjkk()) {
                if (scanSuccess) {

                    jumpNext();
                    scanSuccess = false;
                } else {
                    if (GlobalConts.isNetworkAvailable(getActivity())) {
                        if (TextUtils.isEmpty(GlobalConts.getUrlJMDZJKK())) {
                            noAddressDzjmjkk();

                        } else {
                            SimpleDateFormat dataBirth = new SimpleDateFormat("yyyyMMdd");
                            String dataBir = dataBirth.format(userInfo.getBIRTHDAY());
                            String data_arg1 = "<request><name>" + userInfo.getCUSTOMERNAME() + "</name><telephone>"
                                    + userInfo.getPHONE() + "</telephone><id_number>" + userInfo.getIDCARD()
                                    + "</id_number><id_type>01</id_type><id_card>" + userInfo.getIDCARD()
                                    + "</id_card><nation>" + userInfo.getNATION().replace("DM01-01_", "")
                                    + "</nation><sex>" + userInfo.getSEX().replace("DM01-08_", "") + "</sex><birthday>"
                                    + dataBir + "</birthday><address>" + userInfo.getHOUSEHOLD_ADDR()
                                    + "</address><auth_id_card>" + SPUtil.getstr_jdrIdcard(getActivity()) // 610125198907208102
                                    + "</auth_id_card><auth_name>" + SPUtil.getstr_jdr(getActivity())
                                    + "</auth_name></request>";//
                            getWebServiceJMJKKData(data_arg1, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC);

                        }
                    } else {
                        jumpNext();
                    }
                }
            } else {
                jumpNext();
            }

        } else {
            // 数据已存在
            ((AddCustomerActivity) getActivity()).showTextDialog("数据已存在，不需要建档");
            return;

        }
        getActivity().finish();
    }

    /**
     * 保存选择 的单位信息
     **/
    private void saveDanweiInfo() {
        String docdw = "";
        String jddwno = "";
        if (code02.equals("")) {
            jddwno = code01;
            docdw = name01;
        } else {
            jddwno = code02;
            docdw = name02;
        }

        if (TextUtils.isEmpty(docName) || TextUtils.isEmpty(docId)) {
            showTextDialog("请选择机构及人员");
            return;
        }
        // 保存选中信息
        saveID(docdw, jddwno, docName, docId, str_QuId.replace("-", ""), docPassward, docUsername, docIDCard);
    }

    /**
     * 保存数据信息 no 为对应的编号
     *
     * @param str_xz   乡镇
     * @param str_cz   村庄
     * @param str_jddw 建档单位
     * @param str_jdr  建档人
     * @param jdrno    建档人编号 str_ssqno 省市区编号----对应 个人档案编号 str_jdpassward 密码 str_xzq
     *                 行政区编号【用于更新数据库】
     * @author 王婷婷
     * @date 2015年12月10日 下午3:41:38
     */
    private void saveID(String str_jddw, String str_jddwno, String str_jdr, String str_jdrno, String str_xzq,
                        String str_jdpassward, String str_jdrusername,
                        String str_jdrIDCard) {
        SharedPreferences sp = getActivity().getSharedPreferences(SPUtil.SP_NAME, 0);
        sp.edit().putString(SPUtil.STR_JDDW, str_jddw)
                .putString(SPUtil.STR_JDRNO, str_jdrno)
                .putString(SPUtil.STR_JDDWNO, str_jddwno)
                .putString(SPUtil.STR_JDR, str_jdr)
                .putString(SPUtil.STR_XZQ, str_xzq)
                .putString(SPUtil.STR_JDPADDWARD, str_jdpassward)
                .putString(SPUtil.STR_JDRUSERNAME, str_jdrusername).putString(SPUtil.STR_JDRIDCARD, str_jdrIDCard)
                .commit();
    }

    /**
     * 未检测到电子居民健康卡地址
     *
     * @author 王婷婷
     * @date 2017年12月26日 下午2:17:26
     */
    private void noAddressDzjmjkk() {
        new CommomDialog(getActivity(), R.style.dialog, "经检测，未找到电子居民健康卡接口地址，是否去设置？",
                new CommomDialog.OnCloseListener() {

                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            Intent intent = new Intent(getActivity(), SystemSettingJMDZDAActivity.class);
                            getActivity().startActivity(intent);
                            dialog.dismiss();
                        } else {
                            Intent intent = new Intent(getActivity(), QYInfo.class);
                            getActivity().startActivity(intent);
                            dialog.dismiss();
                        }

                    }

                }).setTitle("温馨提示").setPositiveButton("去设置").setNegativeButton("取消").show();
    }

    /**
     * 获取服务条目data
     *
     * @author 王婷婷
     * @date 2017年5月31日 下午1:48:17
     */
//    private void getCJDAData(final String nation) {
//        final String sex = userInfo.getSEX().equals("DM01-08_1") ? "1" : "2";
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        final String birthday = sdf.format(userInfo.getBIRTHDAY());
//
//        // final String str_jdrUserName = sp.getString("str_jdrUserName", "");
//        final String str_jdrUserName = SPUtil.getstr_jdrusername(getContext());
//        saveFailUserData(str_jdrUserName, birthday, nation, sex);
//
//    }

    /**
     * 保存失败的user数据
     */
    private void saveFailUserData(String str_jdrUserName, String birthday, String nation, String mysex) {
        String strWhere = "cardNum LIKE '" + userInfo.getIDCARD() + "'";
        List<JTYS_BASEINFO> infos = fDbManager.findAllByWhere(JTYS_BASEINFO.class, strWhere);
        if (infos.size() > 0) {
            fDbManager.delete(infos.get(0));
        }

        JTYS_BASEINFO info = new JTYS_BASEINFO();
        info.setID(GlobalContsJTYS.getUUID());
        info.setCardNum(userInfo.getIDCARD());
        info.setYsLoginNumber(str_jdrUserName);
        info.setName(userInfo.getCUSTOMERNAME());
        info.setSex(mysex);
        info.setBirthday(birthday);
        info.setAddress(userInfo.getHOUSEHOLD_ADDR());
        info.setOfficeId(NovaApplication.getJgbh());
        info.setNation(nation);
        info.setSign("0");
        info.setSource("0");
        info.setPopulationType(userInfo.getPOPULATION_TYPE());
        info.setTel(userInfo.getPHONE());
        String datetimeNow = GlobalContsJTYS.datetimeFormat.format(new Date());
        info.setUpdatedate(datetimeNow);
        info.setUpdater(NovaApplication.getJgrno());
        info.setCreatedate(datetimeNow);
        info.setCreater(NovaApplication.getJgrno());
        fDbManager.save(info);
    }

    /**
     * 显示文本信息
     */

    private NovaTextDialog textDialog;

    public void showTextDialog(String text) {
        if (this.textDialog == null)
            this.textDialog = new NovaTextDialog(getActivity());
        this.textDialog.setText(text);
        this.textDialog.show();
    }

    private void jumpNext() {

        cleanData();

        NovaApplication.setUserInfo(userInfo);
        setSaveIDCard(userInfo.getIDCARD());
        saveJTYSUserData();
//		Intent intent = new Intent(getActivity(), QYInfo.class);
//		startActivity(intent);

    }

    /**
     * 保存创建档案数据
     *
     * @author 王婷婷
     * @date 2017年7月26日 下午9:05:19
     */
    private void saveJTYSUserData() {
        try {

            List<JTYS_BASEINFO> jtysUsers = NovaApplication.fdbmanger.findAllByWhere(JTYS_BASEINFO.class,
                    "cardNum='" + userInfo.getIDCARD() + "'");
            if (jtysUsers.size() > 0) {
                // 本地数据已存在
                return;
            }

            final String sex = userInfo.getSEX().equals("DM01-08_1") ? "1" : "2";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            final String birthday = sdf.format(userInfo.getBIRTHDAY());

            String nation = "";
            String nationId = userInfo.getNATION();
            if (!TextUtils.isEmpty(nationId)) {
                List<BD_DD_INFO> minzuInfos = NovaApplication.fdbmanger.findAllByWhereInInfoDB(BD_DD_INFO.class,
                        "ID = " + "'" + nationId + "'");
                if (minzuInfos.size() > 0) {
                    nation = minzuInfos.get(0).getDATAINFO();
                }
            }
            final String str_jdrUserName = SPUtil.getstr_jdrusername(getActivity());// sp.getString("str_jdrUserName",
            // "");
            JTYS_BASEINFO info = new JTYS_BASEINFO();
            info.setID(GlobalContsJTYS.getUUID());
            info.setCardNum(userInfo.getIDCARD());
            info.setYsLoginNumber(str_jdrUserName);
            info.setName(userInfo.getCUSTOMERNAME());
            info.setSex(sex);
            info.setBirthday(birthday);
            info.setAddress(userInfo.getHOUSEHOLD_ADDR());
            info.setOfficeId(NovaApplication.getJgbh());

            info.setNation(nation);
            info.setSign("0");
            info.setSource("0");
            info.setPopulationType(userInfo.getPOPULATION_TYPE());
            info.setTel(userInfo.getPHONE());
            String datetimeNow = GlobalContsJTYS.datetimeFormat.format(new Date());
            info.setUpdatedate(datetimeNow);
            info.setUpdater(NovaApplication.getJgrno());
            info.setCreatedate(datetimeNow);
            info.setCreater(NovaApplication.getJgrno());
            NovaApplication.fdbmanger.save(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存数据
     *
     * @author 王婷婷
     * @date 2017年5月31日 下午4:17:19
     */
    private void saveDatas() {
//		String qysj = ed_date.getText().toString();
//		if (TextUtils.isEmpty(qysj)) {
//			showTextDialog("请选择签约时间");
//			return;
//		}
//		String qyStartsj = ed_start_service.getText().toString();
//		if (TextUtils.isEmpty(qyStartsj)) {
//			showTextDialog("请选择服务开始时间");
//			return;
//		}
//		String qyStopsj = ed_stop_serverce.getText().toString();
//		if (TextUtils.isEmpty(qyStopsj)) {
//			showTextDialog("请选择服务结束时间");
//			return;
//		}
//
//		if (compareData(qyStartsj, qyStopsj)) {
//			ed_stop_serverce.setText("");
//			showTextDialog("服务开始时间不能大于服务结束时间");
//			return;
//		}

//		String ckid_jc = ((QY_fwxmb_jcFragment) jcFragment).getCheckIDs();
//		String ckid_df = ((QY_fwxmb_dfxzFragment) dfxzFragment).getCheckIDs();
//		String ckid_zz = ((QY_fwxmb_zzFragment) zzFragement).getCheckIDs();
//		if (!hasServicePackage()) {
//			new AlertDialog.Builder(QYInfo.this).setTitle(getString(R.string.alert_dialog_titile))// 设置对话框标题
//					.setMessage(getString(R.string.main_activity_message_1))// 设置显示的内容
//					.setPositiveButton(getString(R.string.enter), new DialogInterface.OnClickListener() {// 添加确定按钮
//						@Override
//						public void onClick(DialogInterface dialog, int which) {// 确定按钮的响应事件
//							startActivity(new Intent(QYInfo.this, DataDownLoadMainActivity.class));
//						}
//					}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {// 添加返回按钮
//				@Override
//				public void onClick(DialogInterface dialog, int which) {// 响应事件
//				}
//			}).show();// 在按键响应事件中显示此对话框
//			return;
//		}
//		if (TextUtils.isEmpty(ckid_zz) && TextUtils.isEmpty(ckid_df) && TextUtils.isEmpty(ckid_jc)) {
//			showTextDialog("请选择服务项目");
//			return;
//		}
//		String checkIds = ckid_jc + (TextUtils.isEmpty(ckid_df) ? "" : "," + ckid_df)
//				+ (TextUtils.isEmpty(ckid_zz) ? "" : "," + ckid_zz);
//		Log.e(TAG, checkIds);
//		Log.e("tag", "checkIds" + checkIds);
//		String bz = ((QY_fwxmb_bzFragment) bzFragement).getBz();
        JTYSCustomerDoctorCont cont = new JTYSCustomerDoctorCont();

        cont.setId(GlobalConts.getUUID());
//		cont.setQysj(GlobalConts.getDateName(ed_date.getText().toString()));
//		Log.e(TAG, "pos:" + pos_doc);
//		cont.setQyys(NovaApplication.getDoctorList().get(pos_doc).getUSER_NAME());
//		cont.setQyysdh(doc_phone_edit.getText().toString());
//		cont.setDetailId(checkIds);
        String datetimeNow = GlobalConts.datetimeFormat.format(new Date());
        cont.setUpdatedate(datetimeNow);
//		cont.setUpdater(SPUtil.getstr_jdrusername(this));
        cont.setCreatedate(datetimeNow);
//		cont.setCreater(SPUtil.getstr_jdrusername(this));
        cont.setSign("0");
        cont.setSource("0");
//		cont.setBz(bz);
        cont.setCardNum(NovaApplication.getUserInfo().getIDCARD());
        cont.setCreaterorg(SPUtil.getStrjddwno(getActivity()));
//		cont.setBeginservictime(GlobalConts.getDateName(ed_start_service.getText().toString()));
//		cont.setRes2(GlobalConts.getDateName(ed_stop_serverce.getText().toString()));
//		cont.setRes3(uuid);
        Log.w(TAG, cont.toString());
//		if (flagSave == 0) {
        NovaApplication.fdbmanger.save(cont);
        showTextDialog("保存成功");
//			// flagSave = 1;
//			setFlagSave(1);
//		} else {
//			NovaApplication.fdbmanger.updata(cont, "cardNum='" + NovaApplication.getUserInfo().getIDCARD() + "'");
//			showTextDialog("修改成功");
//		}

        userInfo.setDISTRICT_ID(cont.getId());
//		NovaApplication.fdbmanger.updata(userInfo);
    }

    /**
     * 保存用户信息
     *
     * @author 王婷婷
     * @date 2017年3月2日 下午2:31:02
     */
    private void saveUserOrg() {
        userInfo.setCREATER(docId);//建档人no
        userInfo.setCREATEORG(code02.isEmpty() ? code01 : code02);//建档人单位no
        userInfo.setCREATED_BY(docId);
        userInfo.setCARDTYPE("0");
        userInfo.setTOWNNAME(SPUtil.getstr_xz(getContext()));
        userInfo.setVILLAGENAME(SPUtil.getstr_cz(getContext()));
        userInfo.setCREATEUNIT_NAME(code02.isEmpty() ? name01 : name02);//建档人单位
        userInfo.setCREATEMEN_NAME(docName);//建档人姓名
        userInfo.setDOCTOR(docId);
        try {
            userInfo.setLAST_UPDATE_DATE(
                    GlobalConts.datetimeFormat.parse(GlobalConts.datetimeFormat.format(new Date())));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        userInfo.setLAST_UPDATE_BY(docId);

        userInfo.setPROVINCE(SPUtil.getstr_p(getContext()));
        userInfo.setCITY(SPUtil.getstr_c(getContext()));
        userInfo.setCOUNTY(SPUtil.getstr_n(getContext()));
        userInfo.setSTREET(SPUtil.getstr_xzno(getContext()));

        userInfo.setCOMMITTEE(SPUtil.getstr_czno(getContext()));

        SharedPreferences sp = getContext().getSharedPreferences(SPUtil.SP_NAME, 0);

        sp.edit().putString(SPUtil.STR_JDDW, name01)
                .putString(SPUtil.STR_CZNO, name02)
                .putString(SPUtil.STR_JDRNO, docId)
                .putString(SPUtil.STR_JDDWNO, code02)
                .putString(SPUtil.STR_JDR, docName)
                .putString(SPUtil.STR_JDPADDWARD, docPassward)
                .putString(SPUtil.STR_JDRUSERNAME, docUsername)
                .putString(SPUtil.STR_JDRIDCARD, docIDCard)
                .commit();

    }

    /**
     * 保存idcard
     *
     * @param str_idCard
     * @author 王婷婷
     * @date 2017年6月9日 上午11:55:58
     */
    private void setSaveIDCard(String str_idCard) {
        SPUtil.setstr_idCard(getActivity(), str_idCard);
    }

    /**
     * 添加首次数据
     *
     * @author 王婷婷
     * @date 2017年6月21日 下午6:49:54
     */
    private void saveUserInfo(String idNo, String name, String birthday, String addr, String minzu) {

        userInfo.setSEX(("男").equals(sex) ? "DM01-08_1" : "DM01-08_2");

        userInfo.setIDCARD(idNo);
        userInfo.setCUSTOMERNAME(name);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthdayDate;
        try {
            birthdayDate = sdf.parse(birthday);
            userInfo.setBIRTHDAY(birthdayDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        List<BD_DD_INFO> minzuInfos = fDbManager.findAllByWhereInInfoDB(BD_DD_INFO.class,
                "DATAINFO = " + "'" + minzu + "'");
        userInfo.setNATION(minzuInfos.get(minzuInfos.size() - 1).getID());
        userInfo.setARCHIVEID(SPUtil.getstr_ssqno(getContext()));
        userInfo.setHOUSEHOLD_ADDR(addr);
        userInfo.setMINORITY(minzu);
        userInfo.setIS_UPDATE("Y");
    }

    /**
     * 设置孕妇选择框是否可见
     *
     * @param sex
     * @author 王婷婷
     * @date 2017年9月22日 上午10:13:18
     */
    private void setISycfVisible(String sex) {
        if ("女".equals(sex)) {
            check_isycf.setChecked(false);
            Log.e(TAG, "" + age);
            if (age >= 14 && age <= 55) {
                linear_sfycf.setVisibility(View.VISIBLE);
            } else {
                linear_sfycf.setVisibility(View.GONE);
            }

        } else {
            linear_sfycf.setVisibility(View.GONE);
            check_isycf.setChecked(false);
        }

    }

    /**
     * 保存人群疾病类型
     *
     * @author 王婷婷
     * @date 2017年9月22日 上午10:15:30
     */
    private void saveJBLX() {
        HD_PERSONAL_JKTZ jktz = new HD_PERSONAL_JKTZ();
        if (age >= 14 && age <= 55 && check_isycf.isChecked()) {
            // 孕妇
            jktz.setIsycf(ISTAG);
        } else if (age >= 65) {
            // 老年人
            jktz.setIslnr(ISTAG);
        } else if (age <= 6) {
            // 儿童
            jktz.setIset(ISTAG);
        }
        jktz.setIdCard(userInfo.getIDCARD());
        fDbManager.save(jktz);
        getPop();
    }

    /**
     * 用户表中 --人群分类（用作 家庭签约医生）
     *
     * @param idNo
     * @author 王婷婷
     * @date 2017年3月2日 下午2:42:35
     */
    private void getPop() {
        String population = "";
        if (age >= 14 && age <= 55 && check_isycf.isChecked()) {
            population = PeopleType.WOMAN;
        } else if ((age) >= 65) {
            population = PeopleType.OLD;
        } else if (age <= 6) {
            population = PeopleType.CHILD;
        } else {

        }
        if (!TextUtils.isEmpty(userInfo.getPOPULATION_TYPE())) {
            if (population.equals(PeopleType.YBRQ)) {
                // 一般人群
                return;
            }
            String pop = userInfo.getPOPULATION_TYPE();
            String[] pops = pop.split(",");
            if (!Arrays.asList(pops).contains(population)) {
                pop = pop + "," + population;
                userInfo.setPOPULATION_TYPE(pop);
            }
        } else {
            userInfo.setPOPULATION_TYPE(population);
        }

    }

    /**
     * 注册电子居民健康卡---------------------start--------------------------------------
     */

    private void initProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity());
        // progressDialog.setIcon(R.drawable.ic_launcher);
        mProgressDialog.setTitle("正在同步数据");
        mProgressDialog.setMessage("请稍候...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {

            if (requestCode == 2046) {
                String str_result = data.getStringExtra("resultString");
                if (TextUtils.isEmpty(str_result)) {
                    return;
                }
                Log.e(TAG, "onActivityResult():" + str_result);
                if (NovaApplication.isBoolean_dzjmjkk()) {
                    if (TextUtils.isEmpty(GlobalConts.getUrlJMDZJKK())) {
                        noAddressDzjmjkk();

                    } else {
                        // 扫描结果进行处理
                        String data_arg1 = "<request><qr_code>" + str_result + "</qr_code></request>";
                        getWebServiceJMJKKData(data_arg1, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETDATA_FROMCODEIMG);
                    }
                }
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);

    }

    /**
     * 获取权限
     */
    public void getQuanXian() {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA},
                    CAMERA_REQUEST_CODE);
        } else {
            Intent intent = new Intent(getActivity(), CaptureActivity.class);
            startActivityForResult(intent, 2046);
        }
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, 2046);
            } else {
                GlobalConts.showToast(getActivity(), "操作摄像头权限，已被禁止");
            }
        }
    }

    /**
     * 居民电子健康卡 注册、扫描、获取二维码
     *
     * @param data_arg1
     * @param type
     * @author 王婷婷
     * @date 2017年12月18日 下午5:51:17
     */
    private void getWebServiceJMJKKData(final String data_arg1, final String type) {
        if (TextUtils.isEmpty(type)) {
            return;
        }

        String dataCurrentTime = GlobalConts.datetimeFormat.format(new Date());

        /**
         * bussinessCode 电子居民健康卡注册 RHC_E0001 电子居民健康卡二维码 RHC_E0002 电子居民健康卡的二维码验证
         * RHC_E0003 电子居民健康卡注销 RHC_E0004 电子居民健康卡二维码获取 RHC_E0005 电子居民健康卡注册（现场认证）
         * RHC_E0006
         *
         */
        String progressDialogtitleMsg = "";
        String bussinessCode = "";
        if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC.equals(type)) {
            bussinessCode = "RHC_E0006";
            progressDialogtitleMsg = "正在注册电子居民健康卡信息...";
        } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEIMAGE_FROMIDCARD.equals(type)) {
            bussinessCode = "RHC_E0002";
            // progressDialogtitleMsg="正在获取电子居民健康卡信息...";
        } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETDATA_FROMCODEIMG.equals(type)) {
            bussinessCode = "RHC_E0003";
            progressDialogtitleMsg = "正在获取电子居民健康卡信息...";
        }

        final String data_arg0 = "<request><msgGuid>" + GlobalConts.getUUID()
                + "</msgGuid><msgType>1</msgType><bussinessCode>" + bussinessCode + "</bussinessCode><msgCreateTime>"
                + dataCurrentTime + "</msgCreateTime><orgId></orgId><appCode>"
                + WebServiceConts.WEBSERVICE_DZJMJKK_APPCODE + "</appCode><userName>"
                + WebServiceConts.WEBSERVICE_DZJMJKK_USERNAME + "</userName><userPwd>"
                + WebServiceConts.WEBSERVICE_DZJMJKK_USERPWD + "</userPwd><stdVerCode>1.1</stdVerCode></request>";// ]]>
        initProgressDialog();
        ((AddCustomerActivity) getActivity()).showProgressDialog(progressDialogtitleMsg);
        Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                // System.out.println("webservice");
                try {
                    new JmdzjkkWebService(getActivity()) {

                        @Override
                        public void start(String message) {
                            super.start(message);
                            System.out.println("test111" + message);

                        }

                        @Override
                        public void onSynchronize(String message, int syncCount, int dataSize) {
                            super.onSynchronize(message, syncCount, dataSize);
                        }

                        @Override
                        public void complete(final String message) {
                            super.complete(message);
                            Log.e(TAG, message);
                            ((AddCustomerActivity) getActivity()).cancelProgressDialog();
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                                mProgressDialog.cancel();
                            }
                            ((AddCustomerActivity) getActivity()).runOnUiThread(new Runnable() {

                                @Override
                                public void run() {

                                    if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_ZC.equals(type)) {
                                        // 注册
                                        getZcDataResult(message);
                                    } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEIMAGE_FROMIDCARD
                                            .equals(type)) {
                                        // 申请二维码信息
                                        getZcQcodeImageDataResult(message);
                                    } else if (WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETDATA_FROMCODEIMG
                                            .equals(type)) {
                                        // 通过二维码读取用户信息
                                        getDataQcodeResult(message);
                                    }

                                }

                            });
                        }

                        public void onError(String message) {
                            ((AddCustomerActivity) getActivity()).cancelProgressDialog();
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                                mProgressDialog.cancel();
                            }
                            ((AddCustomerActivity) getActivity()).runOnUiThread(new Runnable() {

                                @Override
                                public void run() {

                                }
                            });
                        }

                        ;
                    }.synchrodata(data_arg0, data_arg1);// ,WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEDATA
                } catch (Exception e) {
                    e.printStackTrace();
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                        mProgressDialog.cancel();
                    }
                    ((AddCustomerActivity) getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // resultDialog.setText("数据同步失败");
                            // resultDialog.showCancleLong();
                        }
                    });
                }

            }
        };
        handler.sendMessage(new Message());

    }

    /**
     * 获取 二维码成功之后的数据处理
     *
     * @param message
     * @author 王婷婷
     * @date 2017年12月18日 下午6:02:46
     */
    private void getDataQcodeResult(final String message) {
        DZJMJKKXQcodeBean ecg = DzjmjkkDataTool.getDataCodeFromXML(message);
        if (ecg != null) {
            if ("success".equals(ecg.getResult())) {
                scanSuccess = true;
                // "<request><name>" + userInfo.getCUSTOMERNAME() +
                // "</name><telephone>"
                // + userInfo.getPHONE() + "</telephone><id_number>" +
                // userInfo.getIDCARD()
                // + "</id_number><id_type>01</id_type><id_card>" +
                // userInfo.getIDCARD() + "</id_card><nation>"
                // + userInfo.getNATION().replace("", "") + "</nation><sex>"
                // + userInfo.getSEX().replace("DM01-08_", "") +
                // "</sex><birthday>" + dataBir + "</birthday><address>"
                // + userInfo.getHOUSEHOLD_ADDR() + "</address>
                idNoEt.setText(ecg.getId_card());
                nameEt.setText(ecg.getName());
                String birth = ecg.getBirthday();
                if (!TextUtils.isEmpty(birth)) {
                    if (birth.length() == 8) {
                        birth = birth.substring(0, 4) + "-" + birth.substring(4, 6) + "-" + birth.substring(6, 8);
                        birthdayEt.setText(birth);
                    }
                } else {
                    birthdayEt.setText("");
                }
                String strSex = ecg.getSex();
                // 性别：0 未知的性别 1 男性 2 女性 9 未说明的性别

                if (!TextUtils.isEmpty(strSex)) {
                    if ("1".equals(sex)) {
                        mailRadio.setChecked(true);
                    } else if ("2".equals(sex)) {
                        famailRadio.setChecked(true);
                    }
                } else {
                    sexRadio.clearCheck();
                }

                String str_nationId = ecg.getNation();
                if (!TextUtils.isEmpty(str_nationId)) {

                    List<BD_DD_INFO> minzuList = fDbManager.findAllByWhereInInfoDB(BD_DD_INFO.class,
                            "ID = 'DM01-01_" + str_nationId + "'");
                    minzuSpinner.setText(minzuList.get(0).getDATAINFO());
                }

                addressEt.setText(ecg.getAddress());
                // minzuSpinner
                exam_phone.setText(ecg.getTelephone());
            } else {
                scanSuccess = false;
                Toast.makeText(getContext(), ecg.getDesc(), Toast.LENGTH_LONG).show();
            }
        } else {
            scanSuccess = false;
            Toast.makeText(getContext(), "未获取到档案数据 ", Toast.LENGTH_LONG).show();
        }
    }

    DZJMJKKXcrzBean dZJMJKKXcrzBean = null;

    /**
     * 获取注册成功之后的数据
     *
     * @param message
     * @author 王婷婷
     * @date 2017年12月18日 下午6:04:54
     */
    private void getZcDataResult(final String message) {
        dZJMJKKXcrzBean = DzjmjkkDataTool.getZCDataFromXML(message);
        if (dZJMJKKXcrzBean != null) {
            if ("success".equals(dZJMJKKXcrzBean.getResult())) {

                String data_arg1 = "<request><id_card>" + userInfo.getIDCARD()
                        + "</id_card><qrcode_type>1</qrcode_type></request>";
                getWebServiceJMJKKData(data_arg1, WebServiceConts.WEBSERVICE_DZJMJKK_TYPE_GETCODEIMAGE_FROMIDCARD);

            } else {
                if (dZJMJKKXcrzBean.getDesc() != null) {
                    Toast.makeText(getActivity(), dZJMJKKXcrzBean.getDesc(), Toast.LENGTH_LONG).show();
                }
                jumpNext();
            }
        } else {
            jumpNext();
        }
    }

    /**
     * 获取注册成功之后的数据
     *
     * @param message
     * @author 王婷婷
     * @date 2017年12月18日 下午6:04:54
     */
    private void getZcQcodeImageDataResult(final String message) {
        DZJMJKKSQCodeImageBean ecg = DzjmjkkDataTool.getZCImageDataFromXML(message);
        if (ecg != null) {
            if ("success".equals(ecg.getResult())) {
                String ecgImageData = ecg.getQr_code_imgtext();
                if (!TextUtils.isEmpty(ecgImageData)) {
                    zcImageCodeSuccessData(ecgImageData);

                } else {
                    zcSuccessData();
                }

            } else {
                zcSuccessData();
            }
        } else {
            zcSuccessData();
        }
    }

    /**
     * 注册成功data
     *
     * @author 王婷婷
     * @date 2017年12月19日 上午9:32:21
     */
    private void zcSuccessData() {
        String str_status = DzjmjkkDataTool.zcSuccessPubData(dZJMJKKXcrzBean);
        Toast.makeText(getContext(), "注册电子居民健康卡成功，审核状态为: " + str_status, Toast.LENGTH_LONG).show();
        new CommomDialog(getActivity(), R.style.dialog, "", new CommomDialog.OnCloseListener() {

            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    jumpNext();
                    dialog.dismiss();
                }

            }

        }).setTitle("关注电子居民健康卡二维码").setImageContent(R.drawable.qrcode_for_dzjmjkk).setImage2Content("")
                .setPositiveButton("下一步").setNegativeButtonVisibility(View.GONE).show();
    }

    /**
     * 注册成功data 申请二维码
     *
     * @author 王婷婷
     * @date 2017年12月19日 上午9:32:21
     */
    private void zcImageCodeSuccessData(String imgBase64String) {
        String str_status = DzjmjkkDataTool.zcSuccessPubData(dZJMJKKXcrzBean);
        Toast.makeText(getContext(), "注册电子居民健康卡成功，审核状态为: " + str_status, Toast.LENGTH_LONG).show();

        new CommomDialog(getActivity(), R.style.dialog, "", new CommomDialog.OnCloseListener() {

            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    jumpNext();
                    dialog.dismiss();
                }

            }

        }).setTitle("关注电子居民健康卡二维码").setImageContent(R.drawable.qrcode_for_dzjmjkk).setImage2Content(imgBase64String)
                .setPositiveButton("下一步").setNegativeButtonVisibility(View.GONE).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        try {
            if (idCardReader != null) {
                idCardReader.closeDevice();
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spinner_xz:// 6
                code02 = "";
                name02 = "";
                code01 = lstData01.get(position).getORGANCODE();
                name01 = lstData01.get(position).getORGANNAME();
                getCS_XZ_Hospital(2, code01);
                setDataTextView_Hospital();

                break;
            case R.id.spinner_cz:// 7
                code02 = lstData02.get(position).getORGANCODE();
                name02 = lstData02.get(position).getORGANNAME();
                int selectedItemPosition = sp02.getSelectedItemPosition();
                if (0 == selectedItemPosition) {
                    code02 = "";
                }
                setDataTextView_Hospital();
                docName = "";
                docId = "";
                docPassward = "";
                docIDCard = "";
                edDocId.setText("");

                docUsername = "";
                tvDocName.setText("");
                // TODO 初始化下面的employee？？
                break;
            case R.id.spinner_employee:// doc
                docName = listDoc.get(position).getNAME();
                docId = listDoc.get(position).getUSER_ID();
                docPassward = listDoc.get(position).getPASSWORD();
                docIDCard = listDoc.get(position).getIDCARD();
                edDocId.setText(docId);
                docUsername = listDoc.get(position).getUSER_NAME();
                Log.e("---", docName + docId + docPassward + docIDCard + docUsername);
                tvDocName.setText("登录账号：" + docUsername);
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    private class WorkThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!mbStop) {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {

                        if (!ReadCardInfo()) {
                            Log.e("**********", "请放卡...");
                        } else {
                            Log.e("**********", "读卡成功，请放入下一张卡");
                        }
                    }
                });

               /* try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/

            }
        }
    }

    /**
     * 设置省市区编号
     *
     * @author 王婷婷
     * @date 2015年12月8日 下午4:19:34
     */
    private void setDataTextView_Hospital() {
        if ("".equals(code02)) {
            edJgId.setText(code01);
            initDoc(code01);
        } else {
            edJgId.setText(code02);
            initDoc(code02);
        }
    }

    /**
     * 本地缓存医生列表并绑定医生SPinner
     *
     * @param parentId
     * @author 王婷婷
     * @date 2015年12月9日 下午4:00:35
     */
    private void initDoc(String parentId) {
        try {
            listDoc = NovaApplication.fdbmanger.findAllByWhere(BD_ORGANIZE_EMPLOYEE.class,
                    "ORGANCODE='" + parentId + "'");
            int pLength = listDoc.size();
            if (pLength > 0) {
                NovaApplication.setDoctorList(listDoc);// 医生列表赋值
            } else {
            }
            bindSpinner_Doctors();
            edDocId.setText(SPUtil.getStr_jdrno(getActivity()));
            tvDocName.setText(SPUtil.getstr_jdrusername(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 绑定医生列表
     *
     * @author 王婷婷
     * @date 2015年12月9日 下午3:30:40
     */
    public void bindSpinner_Doctors() {
        // 判断当前乡镇在数组中的位置并显示
        DoctorAdapter adapter_p = new DoctorAdapter(getActivity(), listDoc);
        spDoc.setAdapter(adapter_p);
        if (listDoc.size() <= 0) return;
        for (int i = 0; i < listDoc.size(); i++) {
            if (SPUtil.getstr_jdr(getActivity()).equals(listDoc.get(i).getNAME())) {
                spDoc.setSelection(i);
            }
        }
        spDoc.setOnItemSelectedListener(this);
    }

    /**
     * 获取城市乡镇医院 flag 0城市 1乡镇 2城市
     *
     * @param flag
     * @author 王婷婷
     * @date 2015年12月8日 上午11:55:03
     */
    private void getCS_XZ_Hospital(int flag, String parentId) {
        try {

            Log.e("获取城市乡镇医院", flag + "\n" + parentId);
            List<BD_ORGANIZE_INSTITUTION> bd_ORGANIZE_INSTITUTIONAs = fDbManager
                    .findAllByWhere(BD_ORGANIZE_INSTITUTION.class, "PARENTID='" + parentId + "'");
            Log.e("List", bd_ORGANIZE_INSTITUTIONAs.size() + "");
            int pLength = bd_ORGANIZE_INSTITUTIONAs.size();
            if (pLength > 0) {
                if (flag == 0) {
                    listCS_Hospital = bd_ORGANIZE_INSTITUTIONAs;
                    getCS_XZ_Hospital(1, listCS_Hospital.get(0).getORGANCODE());
                } else {
                    bindSpinner_CS_XZ_Hospital(flag, bd_ORGANIZE_INSTITUTIONAs);
                }
            } else {
                listCS_Hospital = new ArrayList<>();
                bindSpinner_CS_XZ_Hospital(flag, bd_ORGANIZE_INSTITUTIONAs);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 判断当前乡镇在数组中的位置并显示
    public void bindSpinner_CS_XZ_Hospital(int flag, List<BD_ORGANIZE_INSTITUTION> bds) {
        if (flag == 1) {
            lstData01 = bds;

            XZ_CZHospitalAdapter adapter_p = new XZ_CZHospitalAdapter(getActivity(), lstData01);
            sp01.setAdapter(adapter_p);
            if (lstData01.size() <= 0) return;
            for (int i = 0; i < lstData01.size(); i++) {
                if (SPUtil.getstr_jddw(getActivity()).equals(lstData01.get(i).getORGANNAME())) {
                    sp01.setSelection(i);
                }
            }
            sp01.setOnItemSelectedListener(this);
        } else if (flag == 2) {
            lstData02 = bds;

            List<BD_ORGANIZE_INSTITUTION> list = new ArrayList<>();
            list = lstData02;
            BD_ORGANIZE_INSTITUTION bd = new BD_ORGANIZE_INSTITUTION();
            bd.setORGANNAME("请选择");
            list.add(0, bd);

            XZ_CZHospitalAdapter adapter = new XZ_CZHospitalAdapter(getActivity(), list);
            sp02.setAdapter(adapter);
            if (lstData02.size() <= 0) return;
            for (int i = 0; i < lstData02.size(); i++) {
                if (SPUtil.getstr_czno(getActivity()).equals(lstData02.get(i).getORGANNAME())) {
                    sp02.setSelection(i);
                }
            }
            sp02.setOnItemSelectedListener(this);

        }
    }

    private boolean ReadCardInfo() {
        try {
            if (!idCardReader.sdtFindCard() || !idCardReader.sdtSelectCard()) {
                return false;
            }
            showTextDialog("正在读卡");
            final IDCardInfo idCardInfo = new IDCardInfo();
            if (idCardReader.sdtReadCard(1, idCardInfo)) {
                idNoEt.setText(idCardInfo.getId());
                nameEt.setText(idCardInfo.getName());
                addressEt.setText(idCardInfo.getAddress());

                return true;
            } else {
                //playSound(9, 0);
            }
            showTextDialog("读卡失败，请重试");
            return false;
        } catch (Exception e) {
            showTextDialog("读卡失败，请检查设备是否运行正常");
            return false;
        }
    }

    /**
     * 初始化蓝牙信息
     *
     * @author 王婷婷
     * @date 2015年12月18日 上午10:41:48
     */
    private void initBlooth() {
        System.out.println("00000000000000000");
        if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Log.w("noticeservice-----------111----", "手机不支持BLE");
        }

        mBluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        // mBluetoothAdapter2 = BluetoothAdapter.getDefaultAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Log.w("noticeservice-----------222----", "手机不支持蓝牙");
        }
        Log.w("noticeservice-----------tt----", "手机支持蓝牙");
        // 开启蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            boolean flag = mBluetoothAdapter.enable();
            // 开启蓝牙成功还是失败
            if (flag) {
                NovaApplication.isBluetoothOpen = true;
            } else {
                NovaApplication.isBluetoothOpen = false;
            }

        } else {
            NovaApplication.isBluetoothOpen = true;
        }
    }
}
